/**
 * 优惠卷兑换和展示 20180103  mxm
 */
define(function(require,exports,module) {
    var myPub = require('./public');

    var oWindow = $(window);
    var oHeader = $('.js_headerBox');               // 头部
    var oFooter = $('.js_footer');                  // 底部
    var oContain = $('.js_contain');                // 页面内容区域
    var oGoTop = $('.js_goTop');                    // 回到顶部
    var oSideBox = $('.js_sideBox');		        // 侧边按钮框
    var oExchangeCoupon = $('.js_exchangeCoupon');  // 判断是兑换优惠券页面的标志
    var oGuessLike = $('.js_guessLike');            // 猜你喜欢
    var oHasData = $('.js_hasData');                // 有优惠券的区域
    var oErrPage = $('.js_errPage');                // 有误页面
    var oCouponList = $('.js_couponList');          // 优惠券列表区域
    var oNomore = $('.js_nomore');                  // 没有更多优惠了
    var oGetMoreCoupon = $('.js_getMoreCoupon');    // 查看更多
    var oBindMobileBg = $('.js_bindMobileBg');                          // 绑定手机号码弹窗

    var oGiftMaTxt = $('.js_giftMaTxt');
    // var oGiftMa_TipTxt = $('.js_giftMa_tipTxt');
    var oSubmitGiftMa = $('.js_submitGiftMa');
    var oGoodsList = $('.js_goodsList');

    var oClearBtn = $('.js_clearBtn');
    var scteenHeight = $(window).height();               // 进入页面就获取页面的高度

    var offTap = true;                                      // 阻止多次点击
    var moreTapOffTime = null;                              // 多次点击定时器
    var Testing = false;                                    // 校验按钮是否可点击
    var maxLength = 6;                                      // 校验输入框的最长内容
    var lazLoading = new myPub.lazLoadingImg();
    var guessLikeUrl = '/m/g/1.0/group/listGoodsByName';    // 猜你喜欢商品列表地址
    var couponUrl = '/m/o/coupon/1.0/user/couponList';      // 优惠券列表地址
    var oCouponBottom = $('.js_couponFixedBottom');         // 底部蓝色按钮
    var isLogin = false;                                    // 在浏览器上假定用户未登录

    // var errorTip = ['年丰大当家优惠券使用说明', '<span class="color_red">优惠劵编号错误，请重新输入</span>'];
    var layerTip = ['在使用优惠劵之前需要绑定您的手机号', '恭喜您，验证通过!'];
    var layerStyle_black = 'background-color:rgba(0,0,0, 0.6); color:#FFFFFF; border:none; border-radius: 5px; min-width: 50%;';

    var resizeTimer = null;
    if(myPub.isWeiXin() || myPub.isAlipayClient() || myPub.isQQClient()){
        isLogin = true;
        oCouponBottom.show();
    }else if(bindMobile && bindMobile == 'bindMobile'){
        isLogin = false;
        oCouponBottom.hide();
    }else{
        isLogin = true;
        oCouponBottom.show();
    }
    // 页面尺寸修改
    oWindow.on('resize',function() {
        // alert('123')
        if (resizeTimer) {
            clearTimeout(resizeTimer)
        }
        resizeTimer = setTimeout(function(){
            oContain.css({
                'padding-top': oHeader.outerHeight(true),
                'padding-bottom' : oFooter.outerHeight(true)
            });
        }, 400);

    });

    myPub.JudgeAppHref($('.js_goHome'));

    // 检测页面参数是否含有 startAliapp 跳转支付宝小程序
    myPub.gotoMiniAlipay();

    // 表单验证
    oGiftMaTxt.on('input propertychange',function() {
        if(!isLogin){
            oGiftMaTxt.val('');
            return
        }
        // alert($('body').height());
        // 通过前端验证 修改提示和改变检测状态
        ValiNumLetter(oGiftMaTxt, function () {
            Testing = false;
            // oGiftMa_TipTxt.html(errorTip[1]);
        }, function () {
            Testing = true;
            // oGiftMa_TipTxt.html(errorTip[0]);
        });

        // 满足指定数字个数开始验证
        if(oGiftMaTxt.val().length >= maxLength) {
           Testing ? oSubmitGiftMa.addClass('active') : oSubmitGiftMa.removeClass('active');
        }
        else {
            oSubmitGiftMa.removeClass('active');
        }
    });

    oGiftMaTxt.focus(function () {
        $('body').css({'height':scteenHeight});
        if(!isLogin){
            oGiftMaTxt.val('');
            oGiftMaTxt.blur();
            oBindMobileBg.show();
        }
    });

    oGiftMaTxt.blur(function () {
        var psdScrollTap_timer = null;
        clearTimeout(psdScrollTap_timer);
        psdScrollTap_timer = setTimeout(function () {
            window.scrollTo(0,document.documentElement.clientHeight);
        },100);
    });

    // 提交按钮操作
    oSubmitGiftMa.hammer().on('tap', function () {
        // 变亮状态 还有active
        if($(this).hasClass('active')) {
            // 防止多次点击
            if(offTap) {
                oGiftMaTxt.blur();
                offTap = false;
                if(typeof bindMobile != "undefined" && bindMobile == "bindMobile"){
                    // 绑定手机弹框
                    myPub.askLayer(layerTip[0], function () {
                        // 立即绑定
                        window.location.href = "/h/login/bindMobile?backHref=/coupon/couponList";
                        myPub.LayerCloseAll();
                    }, function () {
                        // 取消
                        myPub.LayerCloseAll();
                    }, 'no', null, ['立即绑定','取消']);
                }else{
                    // 已经绑定的话 则直接去兑换优惠券
                    exchangeCoupon();
                }

                // 绑定成功提示
                // myPub.TipLayer_noShade(layerTip[1], layerStyle_black);
            }
            clearTimeout(moreTapOffTime);
            moreTapOffTime = setTimeout(function () {
                offTap = true;
            }, 500);
        }else if(oGiftMaTxt.val() == ''){
            myPub.TipLayer("请输入优惠券编号", layerStyle_black);
        }else{
            myPub.TipLayer("请输入正确的优惠券编号", layerStyle_black);
        }
    });

    function exchangeCoupon() {
        var codeSign = oGiftMaTxt.val();
        G_JSON_POST("/coupon/grantCoupon",{codeSign:codeSign},function (data) {
            if(data.count > 0){
                myPub.TipLayerEnd("兑换成功",layerStyle_black,function () {
                    window.location.reload();
                });
                return;
            }else{
                if(data.errMsg != null && data.errMsg.length > 0){
                    myPub.TipLayer(data.errMsg, layerStyle_black);
                    return;
                }else{
                    if(data.couponResultList.length > 0){
                        for(var idx=0;idx<data.couponResultList.length;idx++){
                            if(data.couponResultList[idx].errMsg != null && data.couponResultList[idx].errMsg.length > 0){
                                myPub.TipLayer(data.couponResultList[idx].errMsg, layerStyle_black);
                                return;
                            }
                        }
                        myPub.TipLayer("兑换失败", layerStyle_black);
                        return;
                    }else{
                        myPub.TipLayer("兑换失败", layerStyle_black);
                        return;
                    }
                }
            }
        });
    }

    // 清空按钮操作
    oClearBtn.hammer().on('tap', function () {
        oGiftMaTxt.val('');
        // oGiftMa_TipTxt.html(errorTip[0]);
        oSubmitGiftMa.removeClass('active');
    });


    /* 数字字母验证 */
    function ValiNumLetter(obj,fn1,fn2) {
        var reg = new RegExp("^[a-zA-Z0-9]*$");
        if(!reg.test(obj.val())){
            if(fn1) fn1();
        }
        else{if(fn2) fn2();}
    }


    // 回到过顶部
    oGoTop.hammer().on('tap', function () {
        oContain.eq(0).stop().animate({scrollTop: '0'}, 250);

    });

    // 优惠券
    var couponData = {
        getMoreTap:true,                // 获取更多防止双击
        getMore_timer:null,             // 获取更多定时器
        start: 0,                       // 起始数据
        limit: 3,                       // 第一页加载的数据个数
        moreLimit: 20,                  // 不是第一页优惠券加载的数量
        pagearr: 1,                     // 页数

        // 获取数据
        getData:function(start, limit, fn){
            var _this = this;
            _this.start = start;
            G_JSON_POST(couponUrl,{
                'start': start,
                'limit': limit
            },function (data) {
                var dataItem = data;
                oNomore.eq(0).hide();
                oNomore.eq(2).show();
                // console.log(dataItem);
                if(dataItem.ret.code == '0'){
                    if(_this.pagearr < 2 && dataItem.data.length ==0){
                        oErrPage.show();
                        oHasData.hide();
                        return
                    }
                    if(_this.pagearr > 1){
                        if(dataItem.data.length == 0){
                            oNomore.eq(1).show();
                            oNomore.eq(2).hide();
                            return
                        }
                    }
                    oCouponList.append(_this.couponHtml(dataItem.data));

                    if(dataItem.data.length < limit){
                        oNomore.eq(1).show();
                        oNomore.eq(2).hide();
                    }
                    data = null;
                    if(fn)fn();
                }else{
                    oErrPage.show();
                    oHasData.hide();
                }
            })
        },

        // 点击查看更多
        getMoreEvent:function(){
            var _this = this;
            oGetMoreCoupon.on('click',function () {
                if(_this.getMoreTap){
                    _this.getMoreTap = false;
                    oNomore.eq(2).hide();
                    oNomore.eq(0).show();
                    _this.start = _this.limit + _this.moreLimit*(_this.pagearr-1);
                    _this.pagearr++;
                    // 获取数据
                    _this.getData(_this.start, _this.moreLimit);
                }
                clearTimeout(_this.getMore_timer);
                _this.getMore_timer = setTimeout(function () {
                    _this.getMoreTap = true;
                },500)
            })
        },

        // 优惠券拼接
        couponHtml:function (data) {
            var _this = this;
            var thtml = '';
            for(var i = 0; i< data.length;i++){
                var dataItem = data[i];
                var platHtml = '';                      // 区分商家优惠券还是平台优惠券
                var jumpHref = '';                      // 跳转链接
                if(dataItem.platformCoupon){            // supplierId是0时是平台优惠券
                    platHtml = ' platCoupon';
                }

                // 0跳转uselink, 1跳转商城首页， 2跳转优惠券可使用商品列表
                if(dataItem.linkType == 0){
                    jumpHref = dataItem.useLink
                }else if(dataItem.linkType == 1){
                    jumpHref = BASE_URL+"/home";
                }else if(dataItem.linkType == 2){
                    jumpHref = BASE_URL+"/coupon/couponToUse?couponId="+dataItem.couponId;
                }

                thtml +=
                    '<div class="coupon js_coupon '+platHtml+'" data-couponSn = '+dataItem.couponSn+'>'+
                    '   <div class="couponBox">'+
                    '       <div class="couponInfo HBox BoxCenter">'+
                    '           <div class="couponInfoLeft HBox BoxCenter">'+
                    '               <div class="couponPrice">'+
                    '                   <em>￥</em>'+
                    '                   <span>'+dataItem.costPrice+'</span>'+
                    '                   <p>满'+dataItem.needPrice+'元可用</p>'+
                    '               </div>'+
                    '           </div>'+

                    '           <div class="couponInfoCenter Bflex1 height_100">'+
                    '               <div class="couponUseType">'+
                    '                   <h5 class="singleLine" >'+dataItem.couponName+'</h5>'+
                    '                   <div class="tip_use" >'+
                    '                       <p class="">'+dataItem.limitDescribe+'</p>'+
                    '                   </div>'+
                    '                   <div class="tip_useLimt Bflex1">'+
                    '                       <p>'+myPub.FormatDateTime(new Date(dataItem.beginDate),'minDay','.')+'-'+myPub.FormatDateTime(new Date(dataItem.endDate), 'minDay', '.')+'</p>'+
                    '                   </div>'+
                    '               </div>'+
                    '           </div>'+

                    '           <div class="couponInfoRight HBox BoxCenter">'+
                    '               <div class="useThisCoupon">'+
                    '                   <a href="'+jumpHref+'" class="useThisCouponBtn HBox BoxCenter">' +
                    '                       <span>去使用</span>' +
                    '                   </a>'+
                    '               </div>'+
                    '           </div>'+
                    '       </div>'+
                    '   </div>'+

                    '   <div class="gapBox gapBox_right">'+
                    '       <span class="gap gap_top"></span>'+
                    '       <span class="gap_line"></span>'+
                    '       <span class="gap gap_bot"></span>'+
                    '   </div>'+
                    '</div>';
            }
            return thtml
        }
    };
    if(oExchangeCoupon && oExchangeCoupon.length > 0){
        couponData.getData(couponData.start, couponData.limit);
        couponData.getMoreEvent();
    }

    // 猜你喜欢
    var maybeLike = {
        time_Scroll: null,
        start: 0,                           // 分页开始索引
        limit: 20,                          // 每次加载多少条数据
        loaded: false,                      // 有没有加载过
        loadNum: 0,                         // 加载过多少次,全部只能加载5次
        loadComplete: false,                // 是否加载完

        initEvent: function () {
            lazLoading.AddLazLoadingImg(oGoodsList[0]);
            // 导航选中设置
            // oFooter.find('li').eq(3).addClass('active');
            oSideBox.stop().animate({'right': '-3.5rem'}, 300);

        },
        //获取猜你喜欢商品
        getGuessGoods: function (start,type, fn) {
            // type是判断第一次进来还是滚动加载
            var _this = this;
            var data = { start: start, limit: _this.limit, groupName: 'H5_猜你喜欢'};

            //如果是第一次加载
            if(type == 1){
                data = { start: start, limit: _this.limit, isFirst: 1, groupName: 'H5_猜你喜欢'}
            }
            if(_this.loadNum < 5){
                G_JSON_GET(guessLikeUrl,data,function (res) {
                    _this.loadNum++;
                    var result = res.data;
                    if(type == 1){
                        //如果有返回的数据才显示猜你喜欢的部分
                        if(result && result.length > 0){
                            oGuessLike.append(_this.guessBoxHtml());
                            if(result.length >= _this.limit){
                                oGuessLike.find('.js_loadingBtn').hide().eq(1).show();
                            }else {
                                _this.loadComplete = true;
                                oGuessLike.find('.js_loadingBtn').hide().eq(0).show();
                            }
                            oGuessLike.find('.js_goodsList').append(_this.guessGoodsHtml(result));
                        }
                        //如果没数据返回则
                        else {
                            _this.loadComplete = true;
                            return;
                        }
                    }
                    else {
                        if(result && result.length > 0){
                            if(result.length >= _this.limit){
                                oGuessLike.find('.js_loadingBtn').hide().eq(1).show();
                            }else {
                                _this.loadComplete = true;
                                oGuessLike.find('.js_loadingBtn').hide().eq(0).show();
                            }
                            oGuessLike.find('.js_goodsList').append(_this.guessGoodsHtml(result));
                        }else {
                            _this.loadComplete = true;
                            oGuessLike.find('.js_loadingBtn').hide().eq(0).show();
                        }
                    }
                    lazLoading.DestroyLazLoadingImg();
                    lazLoading.AddLazLoadingImg(oContain[0]);
                    if(fn)fn();
                },function (err) {})
            }
            else {
                _this.loadComplete = true;
                oGuessLike.find('.js_loadingBtn').hide().eq(0).show();
            }

        },

        scrollMore: function () {
            var _this = this;
            var oContainScroll = $('.js_contain');
            var minScrHeight = 300;
            oContain.off('scroll');
            oContain.on('scroll',function (e) {
                var afterScroll = $(this).scrollTop();
                // console.log('hhhhaaa',afterScroll);
                _this.ShowGoTop(afterScroll);
                clearTimeout(_this.time_Scroll);
                _this.time_Scroll = setTimeout(function () {

                    // 统计曝光数据
                    // ddjAction.viewGoods( oContain.find('.js_goodsList') );

                    if(oContainScroll[0].scrollHeight - afterScroll - oContainScroll.height() < minScrHeight){
                        if(!_this.loadComplete){
                            _this.start = _this.start + _this.limit;
                            _this.getGuessGoods(_this.start);
                        }
                    }
                },150)
            })
        },
        // 显示回到顶部按钮
        ShowGoTop: function (scrollTop) {
            scrollTop > 300 ? oSideBox.stop().animate({'right': 0}, 300) : oSideBox.stop().animate({'right': '-3.5rem'}, 300);
        },

        //猜你喜欢部分
        guessBoxHtml: function () {
            var shtml = '';
            shtml = '<div class="coupon_service myGuess">'+
                '     <section class="service_title">' +
                '         <p class="titleName">猜你喜欢</p>' +
                '     </section>'+
                '     <div class="goodsGuess_showChangeBox">'+
                '          <div class="goodsGuess_showChange">'+
                '              <ul class="goodsListGuess clearfix js_goodsList">'+
                '              </ul>'+
                '          </div>'+
                '          <div class="moreBtnBox">' +
                '                <p class="loadingBtn js_loadingBtn" style="display: none;"><a>没有更多了</a></p>' +
                '                <p class="loadingBtn js_loadingBtn">' +
                '                     <span class="icon_loading icoStyle icon-spinner3 myRotateRefresh"></span>' +
                '                      <span>加载中</span>' +
                '                  </p>' +
                '            </div>'+
                '      </div>'+
                '</div>';
            return shtml;
        },
        //商品列表
        guessGoodsHtml: function (data) {
            var shtml = '';

            for(var i = 0; i < data.length; i++){
                var item = data[i];
                var quanpeiHtml = '';
                var goodsLabel = '';
                var goodsHref = '';
                var priceHtml = '';
                if(item.tuangou){
                    goodsHref = BASE_URL+'/h/tuangou/goodsDetail/'+item.goodsSn;
                    priceHtml = item.tuangouPrices;
                }else{
                    goodsHref =BASE_URL+'/h/goodspay/goodsView/'+item.goodsSn;
                    // goodsHref = BASE_URL+'/h/goodspay/goodsView/'+item.goodsSn;
                    priceHtml = item.salePrice;
                }
                //如果有全赔图标则显示
                if(item.firstGueeImagePath) {
                    quanpeiHtml = '<div class="quanpei"><img src="https://img.sfddj.com/miniappImg/public/goodsInfo/'+item.firstGueeImagePath+'" alt="" /></div>'
                }

                shtml += '<li>' +
                    '          <a class="" href="'+ goodsHref+'" requestid="'+item.requestId+'"  goodsid="'+ item.goodsId +'">' +
                    '                <figure>' +
                    '                     <img class="js_lazyImg couponGoods" data-echo="'+HTTP_IMAGE_URL + item.goodsDefaultImage + smallImgArg200+'" src="'+ BASE_URL +'/static_v4/image/loadImg.jpg">' +
                    quanpeiHtml +
                    '                 </figure>' +
                    '                 <aside class="priceAreaGuess VBox Bflex1">' +
                    '                      <div class="Bflex1 priceAreaGuess_name">' +
                    '                           <h4>'+item.goodsName+'</h4>' +
                    '                           <p class="smallFont_tip">'+ item.goodsTitle +'</p>' +
                    '                       </div>' +
                    '                       <div class="priceAreaGuess_price">' +
                    '                            <p class="HBox priceAreaBox">' +
                    '                                 <span class="goodsPrice">￥'+ priceHtml +'</span>' +
                    '                             </p>' +
                    '                         </div>' +
                    '                   </aside>' +
                    '            </a>' +
                    '            <p class="addCar js_addCar" pid="'+ item.productId +'"><em class="icon-shopcar_small"></em></p>' +
                    '       </li>';

            }
            return shtml;
        },
    };
    if(oGuessLike && oGuessLike.length > 0){
        maybeLike.initEvent();
        maybeLike.getGuessGoods(maybeLike.start,1, function () {
            maybeLike.scrollMore();
        });
    }

});

